﻿using Evan.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;

namespace Evan.Common.FileManager
{
    /// <summary>
    /// 作者 : 谭远求
    /// 时间 : 2017年5月6日02:33:57
    /// 说明 : 文件管理类 , WebConfig中规定一个目录 , 如果操作跑出目录则拒绝 , 为~为管理整个web
    /// 文件管理类
    /// </summary>
    public class Files
    {

        #region 公有属性
        /// <summary>
        /// 文件管理的根目录
        /// </summary>
        private string _DirPath = "";
        public string DirPath
        {
            get { return this._DirPath; }
        }

        #endregion

        /// <summary>
        /// 根据传入的虚拟路径获取实际的路径
        /// 配置文件中 / 为根目录  如果配置 /uploads/为根目录 
        /// 则前端访问的时候 / 为 /uploads/ 目录
        /// 此方法为根据传入的虚拟路径获取真实路径
        /// </summary>
        /// <param name="DirPath"></param>
        /// <param name="UseAppSettingPath">是否使用AppSetting中配置的路径作为前缀 , 默认使用</param>
        /// <returns></returns>
        private string GetPhysicalPath(string DirPath,bool UseAppSettingPath = true)
        {
            string _Path = "";
            if (UseAppSettingPath)
            {
                _Path = CommFun.GetAppSetting("FileManagerPath");   
            }
            if (string.IsNullOrEmpty(_Path) || _Path == "~" || _Path == "~/" || _Path == "/")
            {
                DirPath = HttpContext.Current.Server.MapPath("~/") + DirPath.TrimStart('/');
            }
            else
            {
                DirPath = HttpContext.Current.Server.MapPath("~/" + _Path.Trim('/') + "/" + DirPath.TrimStart('/'));
            }
            return DirPath;
        }

        /// <summary>
        /// 根据真实的物理路径获取虚拟路径
        /// </summary>
        /// <param name="DirPath"></param>
        /// <returns></returns>
        private string GetVirtualPath(string DirPath)
        {
            string _Path = CommFun.GetAppSetting("FileManagerPath");

            if (string.IsNullOrEmpty(_Path) || DirPath == "~" || DirPath == "~/" || DirPath == "/")
            {
                //不做任何处理
            }
            else
            {
                _Path = _Path.Trim('/');
                _Path = "\\" + _Path;
                DirPath = DirPath.Replace(_Path, "");

                //DirPath = HttpContext.Current.Server.MapPath("~/" + _Path.Trim('/') + "/" + DirPath.TrimStart('/'));
            }

            
            return DirPath;
        }



        #region 构造函数
        public Files(bool UseAppSettingPath = true)
        {
            _DirPath = GetPhysicalPath(DirPath, UseAppSettingPath);
        }

        /// <summary>
        /// / 为根目录  根目录为
        /// </summary>
        /// <param name="DirPath"></param>
        public Files(string DirPath, bool UseAppSettingPath = true)
        {
            _DirPath = GetPhysicalPath(DirPath, UseAppSettingPath);
        }
        #endregion

        #region 获取目录下的文件
        public List<SysModel.FileModel> GetAllByPath()
        {
            return GetAllPath(this._DirPath, null, true);
        }

        public List<SysModel.FileModel> GetAllByPath(string Dir)
        {
            return GetAllPath(Dir, null, true);
        }
        public List<SysModel.FileModel> GetAllByPath(string Dir,string Search)
        {
            return GetAllPath(Dir, Search, true);
        }
        public List<SysModel.FileModel> GetAllByPath(string Dir, string Search,bool IsDir)
        {
            return GetAllPath(Dir, Search, IsDir);
        }
        /// <summary>
        /// 获取目录下面的文件
        /// </summary>
        /// <param name="DirPath">目录名</param>
        /// <param name="SearchPattern">搜索 如 *.txt</param>
        /// <param name="IsDir">是否搜索目录</param>
        /// <returns></returns>
        private List<SysModel.FileModel> GetAllPath(string DirPath,string SearchPattern,bool IsDir)
        {
            
            DirectoryInfo dir;
            if (string.IsNullOrEmpty(DirPath))
            {
                dir = new DirectoryInfo(this._DirPath);
            }
            else {
                dir = new DirectoryInfo(_DirPath + DirPath);
            }
            
            List<SysModel.FileModel> filelist = new List<SysModel.FileModel>();
            
            if (IsAllowPath(dir.FullName))
            {
                filelist.Add(AllowPathTip());
                return filelist;
            }
            
            if (string.IsNullOrEmpty(SearchPattern))
            {
                foreach (FileInfo file in dir.GetFiles("*")) //设置文件类型  
                {
                    filelist.Add(
                        //new SysModel.FileModel { Name = file.Name, FullPath = file.FullName, CurPath = GetVirtualPath(file.DirectoryName.Replace(HttpContext.Current.Server.MapPath("/").TrimEnd('\\'), "")), Type = "File", Suffix = file.Extension, Size = file.Length, AddTime = file.CreationTime, EditTime = file.LastWriteTime }
                        new SysModel.FileModel { Name = file.Name, FullPath = file.FullName, CurPath = (file.DirectoryName.Replace(HttpContext.Current.Server.MapPath("/").TrimEnd('\\'), "")), Type = "File", Suffix = file.Extension, Size = file.Length, AddTime = file.CreationTime, EditTime = file.LastWriteTime }
                        );
                }
            }
            else {
                foreach (FileInfo file in dir.GetFiles(SearchPattern, SearchOption.AllDirectories)) //设置文件类型  
                {
                    filelist.Add(
                        //new SysModel.FileModel { Name = file.Name, FullPath = file.FullName, CurPath = GetVirtualPath(file.DirectoryName.Replace(HttpContext.Current.Server.MapPath("/").TrimEnd('\\'), "")), Type = "File", Suffix = file.Extension, Size = file.Length, AddTime = file.CreationTime, EditTime = file.LastWriteTime }
                        new SysModel.FileModel { Name = file.Name, FullPath = file.FullName, CurPath = (file.DirectoryName.Replace(HttpContext.Current.Server.MapPath("/").TrimEnd('\\'), "")), Type = "File", Suffix = file.Extension, Size = file.Length, AddTime = file.CreationTime, EditTime = file.LastWriteTime }
                        );
                }
            }

            if (IsDir)
            {
                foreach (DirectoryInfo file in dir.GetDirectories("*")) //查找
                {
                    filelist.Add(
                        //new SysModel.FileModel { Name = file.Name, FullPath = file.FullName, CurPath = GetVirtualPath(file.FullName.Replace(HttpContext.Current.Server.MapPath("/").TrimEnd('\\'), "")), Type = "Directory", Suffix = file.Extension, Size = 0, AddTime = file.CreationTime, EditTime = file.LastWriteTime }
                        new SysModel.FileModel { Name = file.Name, FullPath = file.FullName, CurPath = (file.FullName.Replace(HttpContext.Current.Server.MapPath("/").TrimEnd('\\'), "")), Type = "Directory", Suffix = file.Extension, Size = 0, AddTime = file.CreationTime, EditTime = file.LastWriteTime }
                        );
                }
            }

            return filelist;
        }
        #endregion

        public bool CreateFolder(string curDir, string newDir)
        {
           
            //Evan.Common.DirFile.CreateDir(GetPhysicalPath(curDir) + "/" + newDir);
            string dir = GetPhysicalPath(curDir) + "/" + newDir;
            if (dir.Length == 0) { return false; }
            if (!System.IO.Directory.Exists(dir))
            {
                System.IO.Directory.CreateDirectory(dir);
            }
            return true;
        }

        #region 判断是否超出当前目录权限
        /// <summary>
        /// 是否超出了实例化时候设置的目录
        /// </summary>
        /// <param name="Path"></param>
        /// <returns>true = 超出了范围</returns>
        public bool IsAllowPath(string Path)
        {
            return !Path.Contains(_DirPath);
        }
        /// <summary>
        /// 超出的返回提示
        /// </summary>
        /// <returns></returns>
        public SysModel.FileModel AllowPathTip()
        {
            return new SysModel.FileModel { Name = "您无权操作", Type = "Error", Suffix = "Error", Size = 0, AddTime = DateTime.Now, EditTime = DateTime.Now };
        }
        #endregion

    }
}
